'use strict';

import React from 'react';
import { connect } from 'react-redux';
import { Link} from 'react-router';
import * as actions from '../../actions/zhekou1_all_in_list';
import { Button,Icon,Dialog,Pagination,Search,Form,Loading,Menu,Input,Tab} from 'qnui';
import Radio,{ Group as RadioGroup } from 'qnui/lib/radio';
import { Row, Col } from 'qnui/lib/grid';
import Breadcrumb from 'qnui/lib/breadcrumb'
import Step, { Item as StepItem } from 'qnui/lib/step';
import DatePicker, { RangePicker } from 'qnui/lib/date-picker';
import ZhekouTags from 'components/zhekou-tags/index';
import MainNotice from 'components/main-notice/index';
import SystemDialog from 'components/system-dialog/index';
import Tools from 'utils/index';
import linkConfig from 'utils/urls';
import './index.scss';
const links = Tools.isLocal() ? linkConfig.local : linkConfig.onLine;

class Zhekou1AllInList extends React.Component {
    constructor(props) {
        super(props);
		this.dispatch = this.props.dispatch;
        this.state = {
			refreshDialog:false,
			refreshContent:"",
			currentPage:1,
			pageSize:10,
			editActive:false,
			overlayVisible:false,
			tagName:false,
			active:false,
			start_time:false,
			end_time:false,
			zType:false,
			value:0,
        };
    }
	componentWillMount(){
		this.dispatch(
			actions.getList({
				page:1,
				page_size:this.state.pageSize
			})
		);
	}
	onCloseSystemDialog(){
		this.setState({"refreshDialog":false,"orderDialog":false});
		this.props.dispatch(actions.closeDialog());
	}
	handleCheckStatus(){
		return;
	}
	handlePageChange(page){
		this.setState({"currentPage":page});
		this.dispatch(
			actions.getList({
				page:page,
				page_size:this.state.pageSize
			})
		);
	}
	handlePageSizeChange(size){
		this.setState({"currentPage":1,"pageSize":size});
		this.dispatch(
			actions.getList({
				page:1,
				page_size:size
			})
		);
	}
	handleEditActive(active){
		if(active.is_decrease_money){
			this.dispatch(actions.showEditDialog(active));
		}else{
			this.dispatch(
				actions.getActiveDetail({
					activity_id:active.activity_id
				})
			);
		}
	}
	setTag(name){
		this.dispatch(actions.setActiveParam({name}));
	}
	searchResult(hasTag,isPrefect){
		this.setState({"hasTag":hasTag,"isPrefect":isPrefect});
	}
	handleShowSearchTag(){
		this.setState({overlayVisible:true});
	}
	setStartTime(start_time){
		this.dispatch(actions.setActiveParam({start_time}));
	}
	setEndTime(end_time){
		this.dispatch(actions.setActiveParam({end_time}));
	}
	removeActive(activity_id){
		this.dispatch(
			actions.removeActive(activity_id)
		);
	}
	
	checkEndDate(start_time,end_time,callback){
		if(!date){
			callback('必须有一个结束时间');
		}
		if (date && Date.parse(end_time) < Date.parse(start_time)) {
            callback('结束时间必须晚于开始时间！');
        } 
		if (date && Date.parse(end_time) < Date.parse(new Date())) {
            callback('结束时间必须晚于当前系统时间！');
        } 
		{
            callback();
        }
	}
	
	onEditOk(){
		const active = this.props.zhekou1_all_in_list.curActive;
		const active_list = this.props.zhekou1_all_in_list.data.item_promotion_list.item_promotion;
		let last_active ;
		active_list.map((ac)=>{
			if(ac.activity_id == active.activity_id){
				last_active = ac;
			}
		})
		if(active.name!=last_active.name || 
		   active.start_time!=last_active.start_time ||
		   active.end_time!=last_active.end_time ||
		   active.is_discount!=last_active.is_discount ||
		   active.discount_rate!=last_active.discount_rate ||
		   active.is_decrease_money!=last_active.is_decrease_money ||
		   active.decrease_amount!=last_active.decrease_amount ||
		   active.name!=last_active.name)
		{
			// 有任何一样重设则提交请求，否则关闭对话框
			this.dispatch(
				actions.editActive(active)
			);
		}else{
			this.setState({overlayVisible:false,editActive:false});
		}
	}
	onEditCancel(){
		this.dispatch(actions.closeEditDialog());
	}
	amountChange(val,callback){
		// const amountEx = new RegExp(/^\d+(\.([1-9]|\d[1-9]))?$/);
		// if(!amountEx.test(val)){
			 // Dialog.alert({content: '支持2位小数，末尾不为0'});
		// }else{
			this.dispatch(actions.setActiveParam({is_decrease_money:"true",is_discount:"false",decrease_amount:val}));
		// }
	}
	rateChange(val,callback){
		// const rateEx = new RegExp(/^\d{1}(\.([1-9]|\d[1-9]))?$/);
		// if(!rateEx.test(val)){
			 // Dialog.alert({content: '请输入0.01-9.99'});
		// }else{
			this.dispatch(actions.setActiveParam({is_discount:"true",is_decrease_money:"false",discount_rate:val}));
		// }
	}
	tabChange(tab_id){
		console.log(tab_id);
		switch(tab_id){
			case "countdown":	
				　window.location.href=links.ring_tags;
				break;
			case "limit_time":
				break;
			case "mjs1":
				 window.location.href=links.mjs1_list;
				break;
			case "limit_buy":
				 window.location.href=links.limit_buy;
				break;
		}
	}
  render() {
	const data = this.props.zhekou1_all_in_list.data;
	const activitys = data?data.item_promotion_list.item_promotion:[];
	const total = data?parseInt(data.total_count):0;
	const noneMsg = total?"":<Row justify="center">没有任何折扣</Row>;
	
	const tags = <ZhekouTags 
					setTag={this.setTag.bind(this)}	
					search={this.state.search}
					searchResult={this.searchResult.bind(this)}
					curTag={this.state.tagName}
				/>
	const extraContent = <Row>
								    <Button size="large" type="primary" component="a" href="http://www.alibaba.com" target="_blank">
								    <Icon type="pin" /><span>店内打折</span>
									</Button> &nbsp;&nbsp;
									<Button size="large" type="secondary" component="a" href="http://www.alibaba.com" target="_blank">
									    <span>推广打折</span>
									</Button>
								</Row>;
	return (
        <div className="page1-page">
        	<SystemDialog 
				 loginError={this.props.zhekou1_all_in_list.loginError}
			    creating={this.props.zhekou1_all_in_list.creating}
			    message={this.props.zhekou1_all_in_list.message}
			    error={this.props.zhekou1_all_in_list.error}
				 refreshDialog={this.state.refreshDialog}
				 orderDialog={this.state.orderDialog}
		  		 onCloseDialog={this.onCloseSystemDialog.bind(this)}
				/>
			<Dialog style={{width:"680px"}} 
					visible = {this.props.zhekou1_all_in_list.showEditDialog}
                    onOk = {this.onEditOk.bind(this)}
                    onCancel = {this.onEditCancel.bind(this)}
                    onClose = {this.onEditCancel.bind(this)} 
					title = "修改折扣"
					>
					<Row justify="center" style={{marginBottom:"12px"}}>
						<Col span="21">
							<Search 
								 placeholder="选择标签"
								 type="normal"
								 combox={tags}
								 overlayVisible={this.state.overlayVisible}
								 value={this.props.zhekou1_all_in_list.curActive.name}
								 hasIcon={false}
								 searchText="　"
								 autoWidth
								 className="tagSearch"
								 onSearch={()=>{}}
								 onClick={this.handleShowSearchTag.bind(this)}
							/>
						</Col>
					</Row>
					<Row justify="center">
					    <Form labelAlign="inset" span="21">
							<Col span="12">
								<Form.Item label="开始"><DatePicker defaultValue={Date.parse(this.props.zhekou1_all_in_list.curActive.start_time)} onChange={this.setStartTime.bind(this)} placeholder="选择开始时间" showTime/></Form.Item>
							</Col>
							<Col span="12">
								<Form.Item label="结束"><DatePicker defaultValue={Date.parse(this.props.zhekou1_all_in_list.curActive.end_time)} onChange={this.setEndTime.bind(this)} placeholder="选择结束时间"showTime/></Form.Item>
							</Col>
						</Form>
					</Row>
					<Row style={{paddingLeft:"60px"}}>
						<Form.Item style={{width:"132px"}}>
							<Input 
								style={{width:"122px"}}
								size="large" 
								addonBefore="打" 
								state={this.props.zhekou1_all_in_list.curActive.is_discount=="true"?"success":""}
								value={this.props.zhekou1_all_in_list.curActive.discount_rate?this.props.zhekou1_all_in_list.curActive.discount_rate:""}
								onChange={this.rateChange.bind(this)}
								addonAfter="折" 
							/>
						</Form.Item>
						<Form.Item style={{width:"132px"}}>
							<Input 
								style={{width:"122px"}}
								size="large" 
								addonBefore="减" 
								state={this.props.zhekou1_all_in_list.curActive.is_decrease_money=="true"?"success":""}
								value={this.props.zhekou1_all_in_list.curActive.decrease_amount?this.props.zhekou1_all_in_list.curActive.decrease_amount:""}
								onChange={this.amountChange.bind(this)}
								addonAfter="元" 
							/>
						</Form.Item>
					</Row>
            </Dialog>
            <MainNotice />
            <Tab size="medium" type="wrapped" className="my-tab-bar" activeKey="limit_time" tabBarExtraContent={extraContent}  style={{marginTop:"5px"}} onChange={this.tabChange.bind(this)}>
            <Tab.TabPane tab="付款倒计时折扣" key="countdown"></Tab.TabPane>
		    	<Tab.TabPane tab="循环定时打折" key="daily_loop"></Tab.TabPane>
		    	<Tab.TabPane tab="付款打折" key="pay"></Tab.TabPane>
            <Tab.TabPane tab="限时打折" key="limit_time">
					<Row style={{padding:"0"}}>
							<Col span="12">
							{/*
								<RadioGroup defaultValue="onseal" onChange={this.handleCheckStatus.bind(this)}>
									<Radio id="all" value="all">全部</Radio>
									<Radio id="runing" value="runing">进行中</Radio>
									<Radio id="waitting" value="waitting">未开始</Radio>
									<Radio id="stoped" value="stoped">已结束</Radio>
								</RadioGroup>
							*/}
							
							<Button.Group>
								<Link to={"zhekou1_all_in_list"}><Button type="primary">全店打折</Button></Link>
								<Link to={"zhekou1_list"}><Button type="secondary">单品打折</Button></Link>
								<Link to={"zhekou1"}><Button type="secondary">创建活动</Button></Link>
					      </Button.Group>
							</Col>
							<Col span="12">
								 <Pagination current={this.state.currentPage} total={total} pageSize={this.state.pageSize} pageSizeList={[1,10,20,30]} pageSizeSelector="dropdown" type="simple" onChange={this.handlePageChange.bind(this)} onPageSizeChange={this.handlePageSizeChange.bind(this)} />
							</Col>
					</Row>
					<Row align="center" className="list">
						<Col>
							活动标签
						</Col>
						<Col>
							描述
						</Col>
						<Col>
							开始时间
						</Col>
						<Col>
							结束时间
						</Col>
						<Col>
						操作
						</Col>
						<Col fixedSpan="5">
						管理
						</Col>
					</Row>
					{noneMsg}
					{activitys.map((active,key)=>{
						let time = new Date();
						let start_time = new Date(active.start_time);
						let end_time = new Date(active.end_time);
						let is_waitting = time.getTime()<start_time.getTime();
						let is_end = time.getTime()>end_time.getTime();
						let statu = is_waitting?"未开始":(is_end?"已结束":"进行中");
						let color = is_waitting?"#3089DC":(is_end?"#C7C7C7":"#1BB11B");
						const menu = <Menu>
										<Menu.Item key={active.activity_id} onClick={this.removeActive.bind(this)}>删除</Menu.Item>
									</Menu>
						return(
						<Row key={key} align="center" className="list" style={{color:color}}>
							<Col fixedSpan="6">
								{active.name}
							</Col>
							<Col>
								{active.description}
							</Col>
							<Col>
								{active.start_time}
							</Col>
							<Col>
								{active.end_time}
							</Col>
							<Col fixedSpan="5">
								{statu}
							</Col>
							<Col fixedSpan="5">
								<Button.Split size="small" type="secondary" menu={menu} onClick={this.handleEditActive.bind(this,active)}>详情</Button.Split>
							</Col>
						</Row>
						)
					})}
					</Tab.TabPane>
				    <Tab.TabPane tab="满打折/包邮" key="mjs1"></Tab.TabPane>
				    <Tab.TabPane tab="限购优惠" key="limit_buy"></Tab.TabPane>
				    <Tab.TabPane tab="预热折扣" key="5"></Tab.TabPane>
				  </Tab>
        </div>
    );
  }
}


export default connect((state)=> {
  return {
    zhekou1_all_in_list: state.zhekou1_all_in_list
  };
})(Zhekou1AllInList);
